require.config({
    baseUrl:"./",
    paths:{
        jq:"./libs/jquery",
        gg:"./modules/getGoods",
        cr:"./modules/cartRender",
        rl:"./modules/resetLocal",
        ix:"./modules/index1"
    }
})
require(["jq","gg","cr","rl","ix"],function(_, getGoods, render, resetLocal, index1){
    index1();
    const url = "http://localhost:3000/api";
    const tbody = $(".cart-body")
    let goods = localStorage.getItem("goods") ? JSON.parse(localStorage.getItem("goods")) : [];
    getGoods(url,res => {
        res = JSON.parse(res).data.msg;
        render(goods, res, tbody);
        $("#allNum").html(allNum(goods));
        $("#allPrice").html(allPrice(goods));
    })

    tbody.on("click",".del",function(){
        const id = $(this).parent().parent().attr("index");
        $(this).parent().parent().remove();
        
        resetLocal(goods,id,function(i){
            goods.splice(i, 1)
        })

        $("#allNum").html(allNum(goods));
        $("#allPrice").html(allPrice(goods));

        $("#allCheck")[0].checked = allFlag(goods);

    })
    tbody.on("input",".num",function(){
        const id = $(this).parent().parent().parent().attr("index");
        const num = $(this).val()-0;
        console.log(id, num);
        resetLocal(goods,id,function(i){
            goods[i].num = num;
        })


        $("#allNum").html(allNum(goods));
        $("#allPrice").html(allPrice(goods));
    })




        tbody.on("change", ".check", function(){
            const id = $(this).parent().parent().attr("index");
            const flag = this.checked;
            resetLocal(goods, id, function(i){
                goods[i].flag = Number(flag)
            })
            $("#cheAllOne")[0].checked = allFlag(goods);
            console.log(allNum(goods))
            $("#allNum").html(allNum(goods));
            $("#allPrice").html(allPrice(goods));

        })
        $("#cheAllOne")[0].checked = allFlag(goods);
    


        $("#cheAllOne").change(function(){
            goods.forEach(val=>{
                val.flag = Number(this.checked);
            })
            localStorage.setItem("goods", JSON.stringify(goods))
            for(var i=0;i<$(".check").length;i++){
                $(".check")[i].checked = this.checked;
            }
            $("#allNum").html(allNum(goods));
            $("#allPrice").html(allPrice(goods));
        })
})


function allNum(goods){
    // var sum = 0;
    // for(var i=0;i<goods.length;i++){
    //     sum += goods[i].num;
    // }
    // return sum;
    
    return goods.reduce((prev, val)=>{
        return val.flag ? prev + val.num : prev;
    }, 0)
}

function allPrice(goods){
    return goods.reduce((prev, val)=>{
        return val.flag ? prev + val.num * val.price : prev;
    }, 0)
}



function allFlag(goods){
    return goods.every(val=>val.flag)
}

